package com.udaos.modules.field.controllers;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.udaos.common.base.Result;
import com.udaos.common.filter.PrivateFilter;
import com.udaos.common.page.DataTableColumn;
import com.udaos.common.page.DataTableOrder;
import com.udaos.common.util.StringUtil;
import com.udaos.models.area.Ud_area;
import com.udaos.models.field.Ud_field;
import com.udaos.models.field.Ud_field_photo;
import com.udaos.modules.area.services.UdAreaService;
import com.udaos.modules.field.services.UdFieldPhotoService;
import com.udaos.modules.field.services.UdFieldService;
import com.udaos.modules.field.utils.ImageUtils;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

@IocBean
@At("/platform/fieldTrue")
@Filters({ @By(type = PrivateFilter.class) })
public class UdFieldController {

	@Inject
	private UdFieldService fieldService;
	@Inject
	private UdFieldPhotoService fieldPhotoService;
	/*@Inject
	private UdAreaService areaService;*/

	@At("")
	@Ok("beetl:/platform/field/true/index.html")
	@RequiresAuthentication
	public void index() {
		//获取城市信息
		//List<Ud_area> pList=areaService.query();
		//return pList;
	}
	/**
	 * 加載數據列表
	 * @param name
	 * @param length
	 * @param start
	 * @param draw
	 * @param order
	 * @param columns
	 * @return
	 */
	@At
	@Ok("json:full") 
	@RequiresAuthentication
	public Object data(
			@Param("lnglat") String lnglat,@Param("ll") String ll,
			@Param("name") String name,@Param("address") String address, @Param("length") int length, @Param("start") int start,
			@Param("draw") int draw, @Param("::order") List<DataTableOrder> order,
			@Param("::columns") List<DataTableColumn> columns) {
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(name)){
			cnd.and("name", "like", "%" + name + "%");
		}
		if (!Strings.isBlank(address)){
			cnd.and("address", "like", "%" +address + "%");
		}
		if(!Strings.isBlank(ll)){
			System.out.println(ll);
			String [] lls=ll.split(";");
			String [] ll1=lls[0].split(",");
			String [] ll2=lls[1].split(",");
			cnd.and("lng", "between", new Object[]{Double.valueOf(ll1[0]), Double.valueOf(ll2[0])});
			cnd.and("lat", "between", new Object[]{Double.valueOf(ll1[1]), Double.valueOf(ll2[1])});
		}
		return fieldService.data(length, start, draw, order, columns, cnd, null);
	}
	
	/**
	 * 编辑场地
	 * @param id
	 * @return
	 */
	@At("/edit/?")
	@Ok("beetl:/platform/field/true/edit.html")
	@RequiresAuthentication
	public Object edit(String id) {
		Map<String,Object> map=new HashMap<String,Object>();
		
		//获取实体
		Ud_field field= fieldService.fetch(id);
		map.put("field", field);
		//获取图片
		Cnd cnd = Cnd.NEW();
		cnd.and("poi_id", "=", id);
		List<Ud_field_photo> list=fieldPhotoService.query(cnd);
		map.put("photo_list", list);
		
		return map;
	}
	
	@At("/editDo")
	@Ok(">>:/platform/fieldTrue")
	@RequiresAuthentication
	public void editDo(@Param("..") Ud_field field,HttpServletRequest request, @Param("::title") String[] titles, @Param("::url") String[] urls,
			 String deleteIds) {
		fieldService.updateIgnoreNull(field);

		if (!StringUtil.isNullOrEmpty(deleteIds)) {
			// 进行删除操作
			String[] ids = deleteIds.split(";");
			fieldPhotoService.delete(ids);
		}
		if (null != urls) {
			List<Ud_field_photo> photoList = new ArrayList<Ud_field_photo>();
			Map<String, Object> map = ImageUtils.UploadImgFileBase64(urls, 400, request);
			if ((boolean) map.get("status")) {
				List<String> urlList = (List) map.get("url");
				for (int i = 0; i < urlList.size(); i++) {
					Ud_field_photo field_photo = new Ud_field_photo();
					field_photo.setPoi_id(field.getId());
					field_photo.setTitle(titles[i]);
					field_photo.setUrl(urlList.get(i));
					photoList.add(field_photo);
				}
			}
			fieldPhotoService.add(photoList);
		}
	}
	
	/**
	 * 新增场地
	 */
	@At
	@Ok("beetl:/platform/field/true/add.html")
	@RequiresAuthentication
	public void add() {

	}
	
	@At("/addDo")
	@Ok(">>:/platform/fieldTrue")
	@RequiresAuthentication
	public void addDo(@Param("..") Ud_field field,HttpServletRequest request, @Param("::title") String[] titles, @Param("::url") String[] urls) {
		field.setState("0");
		field.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		fieldService.insert(field);

		if (null != urls) {
			List<Ud_field_photo> photoList = new ArrayList<Ud_field_photo>();
			Map<String, Object> map = ImageUtils.UploadImgFileBase64(urls, 400, request);
			if ((boolean) map.get("status")) {
				List<String> urlList = (List) map.get("url");
				for (int i = 0; i < urlList.size(); i++) {
					Ud_field_photo field_photo = new Ud_field_photo();
					field_photo.setPoi_id(field.getId());
					field_photo.setTitle(titles[i]);
					field_photo.setUrl(urlList.get(i));
					photoList.add(field_photo);
				}
			}
			fieldPhotoService.add(photoList);
		}
	}
	
	@At("/delete/?")
	@Ok("json")
	@RequiresAuthentication
	public Object delete(String id, HttpServletRequest req) {
		try {
			Ud_field field = fieldService.fetch(id);
			if (null != field) {
				field.setState("3");
				fieldService.update(field);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}	
	
	/**
	 * 导出
	 * @param lnglat
	 * @param ll
	 * @param name
	 * @return
	 */
	@At
	@RequiresAuthentication
	public void export(
			@Param("lnglat") String lnglat,
			@Param("ll") String ll,
			@Param("name") String name,HttpServletRequest request,HttpServletResponse response){
		//获取数据
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(name)){
			cnd.and("name", "like", "%" + name + "%");
		}
		cnd.and("state","!=","3");
		if(!Strings.isBlank(ll)){
			System.out.println(ll);
			String [] lls=ll.split(";");
			String [] ll1=lls[0].split(",");
			String [] ll2=lls[1].split(",");
			cnd.and("lng", "between", new Object[]{Double.valueOf(ll1[0]), Double.valueOf(ll2[0])});
			cnd.and("lat", "between", new Object[]{Double.valueOf(ll1[1]), Double.valueOf(ll2[1])});
		}
		List<Ud_field> list=fieldService.query(cnd);
		
		try{
			  Long now=System.currentTimeMillis(); 
		      String fname = now.toString();//Excel文件名
		      OutputStream os = response.getOutputStream();//取得输出流
		      response.reset();//清空输出流
		      response.setHeader("Content-disposition", "attachment; filename=" + fname + ".xls");//设定输出文件头
		      response.setContentType("application/msexcel");//定义输出类型
		      WritableWorkbook wbook = Workbook.createWorkbook(os); //建立excel文件
		      WritableSheet wsheet = wbook.createSheet("训练场地表", 0); //sheet名称
		      //设置excel标题
		      WritableFont wfont = new WritableFont(
		          WritableFont.ARIAL, 20,
		          WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
		          Colour.BLACK);
		      WritableCellFormat wcfFC = new WritableCellFormat(wfont);
		      wcfFC.setAlignment(Alignment.CENTRE);//水平居中对齐
		      //竖直方向居中对齐
		      wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);
		      if(null == list || list.size()==0){
		    	  Label wlabel= new Label(0, 0, "暂无数据", wcfFC);//创建单元格设置样式
		    	  wsheet.addCell(wlabel);
		    	  wbook.write(); //写入文件
			      wbook.close();
			      os.close();
			      
			      return;
		      }
		      Label wlabel1= new Label(0, 0, "训练场地表", wcfFC);//创建单元格设置样式
		      //合并单元格，参数依次为：列索引、行索引、列索引+需要合并的列的个数、行索引+需要合并的行的个数
		      wsheet.mergeCells(0, 0, 7, 0);
		      //将单元格添加到工作表wsheet相应的单元格中
		      wsheet.addCell(wlabel1);
		      wfont = new WritableFont(
			          WritableFont.ARIAL, 14,
			          WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
			          Colour.BLACK);
		      WritableCellFormat wcfFC1 = new WritableCellFormat( wfont);
		      //设置单元格宽度，以字符为单位
	          wsheet.setColumnView(0, 40);
	          wsheet.setColumnView(1, 30);
	          wsheet.setColumnView(2, 30);
	          wsheet.setColumnView(3, 30);
	          wsheet.setColumnView(4, 30);
	          wsheet.setColumnView(5, 30);
	          wsheet.setColumnView(6, 30);
	          wsheet.setColumnView(7, 30);
	          wcfFC1.setAlignment(Alignment.CENTRE);//水平居中对齐
	          wcfFC1.setBorder(Border.ALL,BorderLineStyle.THIN); //设置边框
		      wcfFC1.setBackground(Colour.GRAY_25); //设置背景色
		      wsheet.addCell(new Label(0, 1, "场地名称", wcfFC1));//创建单元格设置样式);
		      wsheet.addCell(new Label(1, 1, "类型", wcfFC1));;
		      wsheet.addCell(new Label(2, 1, "地址", wcfFC1));
		      wsheet.addCell(new Label(3, 1, "经度", wcfFC1));
		      wsheet.addCell(new Label(4, 1, "纬度", wcfFC1));
		      wsheet.addCell(new Label(5, 1, "联系电话", wcfFC1));
		      wsheet.addCell(new Label(6, 1, "是否夜训", wcfFC1));
		      wsheet.addCell(new Label(7, 1, "状态", wcfFC1));
		      int i=2;
		      
		      WritableFont wfont1 = new WritableFont(
			          WritableFont.createFont("宋体"), 14,WritableFont.NO_BOLD
			          , false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
		      WritableCellFormat wcfFC2 = new WritableCellFormat( wfont1);
		      wcfFC2.setAlignment(Alignment.CENTRE);//水平居中对齐
		      wcfFC2.setBorder(Border.ALL,BorderLineStyle.THIN); //设置边框
		     
		      for (int j = 0; j < list.size(); j++) {
		    	  Ud_field u=list.get(j);
		    	  wsheet.addCell(new Label(0, i, String.valueOf(u.getName()), wcfFC2));
			      wsheet.addCell(new Label(1, i, String.valueOf(u.getType()), wcfFC2));
		    	  wsheet.addCell(new Label(2, i, String.valueOf(u.getAddress()), wcfFC2));	
		    	  wsheet.addCell(new Label(3, i, String.valueOf(u.getLng()), wcfFC2));	
		    	  wsheet.addCell(new Label(4, i, String.valueOf(u.getLat()), wcfFC2));	
		    	  wsheet.addCell(new Label(5, i, String.valueOf(u.getTel()), wcfFC2));	
		    	  wsheet.addCell(new Label(6, i, String.valueOf(u.getIs_night_train()==1?"是":"否"), wcfFC2));	
		    	  wsheet.addCell(new Label(7, i, String.valueOf(u.getState().equals("1")?"正常":"未核实"), wcfFC2));	
			      i++;
		      }
		      
		      i=2;
		      wbook.write(); //写入文件
		      wbook.close();
		      os.close();
		    }catch(Exception e){
			    return ;
		    }
		
	    return;
		
	}


}
